package com.dy.yunying.biz.service.hongbao.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.constant.DistributedLock;
import com.dy.yunying.api.entity.ParentGameDO;
import com.dy.yunying.api.entity.WanGameDO;
import com.dy.yunying.api.entity.hongbao.*;
import com.dy.yunying.api.enums.ActivityEventEnum;
import com.dy.yunying.api.enums.WithdrawStatusEnum;
import com.dy.yunying.api.enums.WithdrawTypeEnum;
import com.dy.yunying.api.req.ParentGameReq;
import com.dy.yunying.api.req.hongbao.HbWithdrawRecordRejectReq;
import com.dy.yunying.api.req.hongbao.HbWithdrawRecordReq;
import com.dy.yunying.biz.config.YunYingProperties;
import com.dy.yunying.biz.dao.ads.hongbao.*;
import com.dy.yunying.biz.service.hongbao.ActivityService;
import com.dy.yunying.biz.service.hongbao.HbWithdrawRecordService;
import com.dy.yunying.biz.service.manage.GameService;
import com.dy.yunying.biz.service.manage.ParentGameService;
import com.dy.yunying.biz.utils.DateUtils;
import com.dy.yunying.biz.utils.WxPayUtils;
import com.dy.yunying.biz.utils.XMLUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.sjda.framework.common.utils.MD5;
import com.sjda.framework.common.utils.RandomUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 提现记录
 *
 * @author zhuxm
 * @Date 2022-07-11 20:23:15
 */
@Log4j2
@Service("hbWithdrawRecordService")
@RequiredArgsConstructor
public class HbWithdrawRecordServiceImpl extends ServiceImpl<HbWithdrawRecordMapper, HbWithdrawRecord> implements HbWithdrawRecordService {

	private final YunYingProperties properties;

	private final ActivityService activityService;

	private final HbInvestRecordMapper investRecordMapper;

	private final HbReceivingRecordMapper receivingRecordMapper;

	private final HbCashConfigMapper hbCashConfigMapper;

	private final RedissonClient redissonClient;

	private final HbActivityRoleInfoMapper hbActivityRoleInfoMapper;

	private final HbWithdrawRoleInfoMapper hbWithdrawRoleInfoMapper;

	private final KafkaTemplate<String, Object> kafkaTemplate;

	private final ThirdPaySettingMapper thirdPaySettingMapper;

	private final ParentGameService parentGameService;

	private final GameService gameService;

	@Value("${mch.appid:wxbebb3a04c3ed34e9}")
	private String mch_appid;

	@Value("${wx.mchid:1578865251}")
	private String mchid;

	@Value("${wx.key:bf03c6fdfdd7cf06e146aac0f67f7573}")
	private String wxkey;

	@Value("${wx.cert.path:H://Desktop//红包//apiclient_cert.p12}")
	private String wxCertPath;

	@Value("${system.prefix:3367}")
	private String systemPrefix;

	/**
	 * 批量提现审核
	 *
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public R batchReviewer(HbWithdrawRecordRejectReq req) throws Exception {
		String[] ids = req.getIds().split(",");
		int num = 0;
		for (String id : ids) {
			// 审核类型：1通过，2驳回
			if ("1".equals(req.getReviewerType())) {
				R result = this.pass(new HbWithdrawRecordRejectReq().setId(Long.valueOf(id)));
				if (0 != result.getCode()) {
					return R.failed(null, 2, "审核通过" + num + "条，失败：" + (ids.length - num) + "条。失败原因：" + result.getMsg());
				}
			} else if ("2".equals(req.getReviewerType())) {
				R result = this.reject(new HbWithdrawRecordRejectReq().setId(Long.valueOf(id)).setRejectReason(req.getRejectReason()));
				if (0 != result.getCode()) {
					return R.failed(null, 2, "驳回成功" + num + "条，失败：" + (ids.length - num) + "条。失败原因：" + result.getMsg());
				}
			} else {
				return R.failed("未知审核类型");
			}
			num++;
		}
		return R.ok();
	}

	@Override
	public R pass(HbWithdrawRecordRejectReq req) throws Exception {

		HbWithdrawRecord record = this.getById(req.getId());
		//这里增加了提现状态判断，避免2个用户不同页面先后提现。
		if (record == null || record.getStatus() != WithdrawStatusEnum.AUDITING.getVal()) {
			return R.failed("提现记录错误");
		}
		//根据活动id增加分布式锁
		final RLock lock = redissonClient.getLock(DistributedLock.WITHDRAW_RECORD_ID_KEY_PREFIX + record.getActivityId());
		//第一个锁为最多等待时间(多次点击执行时间超时返回false)，第二个时间为自动过期时间
		if (lock.tryLock(DistributedLock.TIMEOUT_FIFTEEN_SEC, TimeUnit.SECONDS)) {
			try {
				HbActivity hbActivity = activityService.getById(record.getActivityId());
				if (hbActivity == null) {
					return R.failed("活动信息错误");
				}
				HbCashConfig hbCashConfig = hbCashConfigMapper.selectById(record.getLevelId());
				if (hbCashConfig == null) {
					return R.failed("提现档次信息错误");
				}

				//20230228 去除提现是否能超过注资金额或总领取红包的现金总额的校验
//				final BigDecimal expendBalance = baseMapper.selectPassedExpendBalance(record.getActivityId()); // 审核通过的已提现金额
//				final Double totalInvestMoney = investRecordMapper.sumInvestMoneyByType(record.getActivityId(), 1); // 注资金额
//				if (record.getMoney().compareTo(BigDecimal.valueOf(Objects.isNull(totalInvestMoney) ? 0 : totalInvestMoney).subtract(expendBalance)) > 0) {
//					return R.failed("活动资金不足，请先注资");
//				}
//				final Double totalExpendBalance = receivingRecordMapper.sumExpendBalanceByType(record.getActivityId(), 1); // 总已领取金额
//				if (record.getMoney().compareTo(BigDecimal.valueOf(Objects.isNull(totalExpendBalance) ? 0 : totalExpendBalance).subtract(expendBalance)) > 0) {
//					return R.failed("个人可提现余额不足");
//				}
				// 从审核中改为提现中
				Date now = new Date();
				HbWithdrawRecord updateBean = new HbWithdrawRecord();
				updateBean.setId(req.getId());
				updateBean.setAuditingId(Long.valueOf(SecurityUtils.getUser().getId()));//审核人
				updateBean.setAuditingTime(now); // 审核时间
				if (baseMapper.updateStatusToWithdrawingById(updateBean) == 0) {
					return R.failed("提现状态错误");
				}
				//商户订单号
				String bizNo = "";
				//第三方订单号
				String thirdOrderId = "";
				//到账时间
				String paymentTime = "";
				try {
					//发送微信接口【每个订单号唯一】
					String openid = record.getOpenid();

					if (WithdrawTypeEnum.WECHAT.getType().equals(record.getType())) {
						Map<String, String> map;
						//前缀【4位-6位】+ 业务系统【4位】+ 日期【6位】+ 提现记录ID【目前是3位，总共可以增加到9位】
						String business = "HBTX";
						String prefix = systemPrefix + business + DateUtils.dateToString(record.getCreateTime(), DateUtils.YYMMDD);
						String recoredId = String.valueOf(record.getId());
						int zeroLength = 32 - prefix.length() - recoredId.length();
						String partnerTradeNo = prefix + RandomUtil.generateZeroStr(zeroLength) + recoredId;
						log.info("提现商品订单号：{}", partnerTradeNo);
						String content = WxPayUtils.payForUser(mch_appid, mchid, RandomUtil.generateLetterStr(32), partnerTradeNo, openid, String.valueOf(record.getMoney().multiply(BigDecimal.TEN).multiply(BigDecimal.TEN).intValue()), "提现", wxkey, wxCertPath);
						log.info("提现返回内容：{}", content);
						map = XMLUtils.doXMLParse(content);
						String result_code = map.isEmpty() ? "" : map.get("result_code");
						if (!"SUCCESS".equals(result_code)) {
							//接口报错，仍然状态为审核中
							String err_code_des = map.get("err_code_des");
							log.error("提现发送微信接口结果信息描述：{}", err_code_des);
							updateBean = new HbWithdrawRecord();
							updateBean.setId(req.getId());
							updateBean.setStatus(WithdrawStatusEnum.AUDITING.getVal()); // 审核中
							updateBean.setPartnerTradeNo(partnerTradeNo);
							updateBean.setErrCode(map.get("err_code"));
							updateBean.setErrCodeDes(map.get("err_code_des"));
							this.updateById(updateBean);
							return R.failed(err_code_des);
						} else {
							bizNo = map.get("partner_trade_no");
							thirdOrderId = map.get("payment_no");
							paymentTime = map.get("payment_time");
						}
					} else if (WithdrawTypeEnum.ALIPAY.getType().equals(record.getType())) {
						//获取支付配置信息
						ThirdPaySetting paySetting = thirdPaySettingMapper.selectOne(Wrappers.<ThirdPaySetting>lambdaQuery()
								.eq(ThirdPaySetting::getAppId,properties.getAliPayWithdrawAppId())
								.eq(ThirdPaySetting::getDeleted,0));
						if (paySetting == null) {
							return R.failed("请联系技术配置支付参数");
						}
						//暂时直接转账，不查询付款账户余额、不查询转账状态，直接利用同步返回的结果
						AlipayClient alipayClient = this.getAlipayClient(paySetting);
						AlipayFundTransUniTransferRequest transferReq = new AlipayFundTransUniTransferRequest();
						AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
						//重复不会转账成功
						model.setOutBizNo(record.getWithdrawNo());
						model.setRemark(paySetting.getRemark());
						Map<String,Object> bpMap = new HashMap<>();
						bpMap.put("payer_show_name_use_alias",true);
						model.setBusinessParams(JSON.toJSONString(bpMap));
						model.setBizScene("DIRECT_TRANSFER");
						Participant payeeInfo = new Participant();
						//先固定 ALIPAY_LOGON_ID 待自动绑定时取HbWithdrawRecord表新加属性
						payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
						//目前手动绑定openid存储的是手机号或邮箱\nickname 存储的是真实姓名
						payeeInfo.setIdentity(openid);
						payeeInfo.setName(record.getNickname());
						model.setPayeeInfo(payeeInfo);
						//订单总金额，单位为元 必须2位小数
						model.setTransAmount(String.valueOf(record.getMoney().setScale(2,RoundingMode.HALF_UP)));
						model.setProductCode("TRANS_ACCOUNT_NO_PWD");
						//"取活动名称+日期+奖励发放" 示例：新春冲级活动20230105奖励发放
						String orderTitle = hbActivity.getActivityName()
								.concat(DateUtils.dateToString(new Date(), DateUtils.YYYYMMDD)
								.concat("奖励发放"));
						model.setOrderTitle(orderTitle);
						transferReq.setBizModel(model);
						log.info("支付宝转账前参数:{}",JSON.toJSONString(transferReq));
						AlipayFundTransUniTransferResponse transferRes = alipayClient.certificateExecute(transferReq);
						log.info("支付宝转账后参数:{}",JSON.toJSONString(transferRes));
						if (transferRes.isSuccess()) {
							bizNo = transferRes.getOutBizNo();
							thirdOrderId = transferRes.getOrderId();
							paymentTime = transferRes.getTransDate();
						} else {
							updateBean = new HbWithdrawRecord();
							updateBean.setId(req.getId());
							updateBean.setStatus(WithdrawStatusEnum.AUDITING.getVal()); // 审核中
							updateBean.setPartnerTradeNo(transferRes.getOutBizNo());
							updateBean.setErrCode(transferRes.getSubCode());
							updateBean.setErrCodeDes(transferRes.getSubMsg());
							this.updateById(updateBean);
							return R.failed("转账失败:" + transferRes.getSubMsg());
						}


					}
				} catch (Throwable t) {
					log.error("提现发送微信接口异常", t);
					// 记录提现为失败。
					updateBean = new HbWithdrawRecord();
					updateBean.setId(req.getId());
					updateBean.setStatus(WithdrawStatusEnum.FAILURE.getVal());
					this.updateById(updateBean);
					return R.failed("提现接口异常，提现失败");
				}

				updateBean = new HbWithdrawRecord();
				updateBean.setId(req.getId());
				updateBean.setStatus(WithdrawStatusEnum.SUCCESS.getVal()); // 成功
				updateBean.setPartnerTradeNo(bizNo);
				updateBean.setPaymentNo(thirdOrderId);
				updateBean.setPaymentTime(StringUtils.defaultIfBlank(paymentTime,DateUtils.dateToString(now,DateUtils.YYYY_MM_DD_HH_MM_SS)));
				updateBean.setPayedTime(now);
				updateBean.setErrCode("");
				updateBean.setErrCodeDes("");
				this.updateById(updateBean);
				// 更新提现成功次数
				hbActivityRoleInfoMapper.updatePassedOnceByRoleKey(new HbActivityRoleInfo()
						.setPgameId(record.getParentGameId().longValue()).setAreaId(record.getAreaId().longValue()).setRoleId(record.getRoleId()).setActivityId(record.getActivityId()).setSourceType(1)
						.setTotalArriveAmount(record.getMoney()).setCashedPassAmount(record.getMoney()));
				hbWithdrawRoleInfoMapper.updatePassedOnceByRoleKey(new HbWithdrawRoleInfoDO().setPgameId(record.getParentGameId().longValue()).setAreaId(String.valueOf(record.getAreaId())).setRoleId(record.getRoleId()).setCashConfigId(record.getLevelId()));
				//统计消耗，统计注资，统计活动
				activityService.sumActivity(record.getActivityId());

				//目前该步骤为异步。
				try {
					final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
					String recordValue = new JSONObject()
							.fluentPut("eventType", ActivityEventEnum.WITHDRAWAL_AUDIT_PASS.getCode())
							.fluentPut("eventTime", sdf.format(now))
							.fluentPut("userId", record.getUserId())
							.fluentPut("username", record.getUsername())
							.fluentPut("pGameId", record.getParentGameId())
							.fluentPut("gameId", record.getGameId())
							.fluentPut("areaId", record.getAreaId())
							.fluentPut("parentChl", record.getParentchl())
							.fluentPut("chl", record.getChl())
							.fluentPut("appChl", record.getAppchl())
							.fluentPut("roleId", record.getRoleId())
							.fluentPut("roleName", record.getRoleName())
							.fluentPut("activityId", record.getActivityId())
							.fluentPut("activityName", hbActivity.getActivityName())
							.fluentPut("activityType", hbActivity.getActivityType())
							.fluentPut("dynamicTypeId", hbActivity.getDynamicTypeId())
							.fluentPut("levelId", record.getLevelId())
							.fluentPut("levelName", hbCashConfig.getCashName())
							.fluentPut("cashType", record.getType())
							.fluentPut("amount", record.getMoney().doubleValue())
							.fluentPut("receiveId", req.getId())
							.toJSONString();
					log.info("提现成功发送kafka信息增加累计提现金额:{}", recordValue);
					kafkaTemplate.send(properties.getActivityEventTopic(), String.valueOf(record.getUserId()), recordValue.getBytes(StandardCharsets.UTF_8));
				} catch (Exception e) {
					log.error("提现成功发送kafka信息增加累计提现金额异常", e);
					throw new Exception("提现成功发送kafka信息增加累计提现金额异常", e);
				}
			} finally {
				lock.unlock();
			}
			return R.ok();
		} else {
			log.error("提现重复提交");
			return R.failed("提交太频繁，请稍后操作");
		}

	}

	private AlipayClient getAlipayClient(ThirdPaySetting paySetting) throws AlipayApiException {
		String privateKey = paySetting.getAppPrivateKey();
		String appPublicCertPath = paySetting.getAppPublicCert();
		String alipayPublicCertPath = paySetting.getThirdPublicCert();
		String alipayRootCertPath = paySetting.getThirdRootCert();
		AlipayConfig alipayConfig = new AlipayConfig();
		alipayConfig.setAppCertPath(appPublicCertPath);
		alipayConfig.setAlipayPublicCertPath(alipayPublicCertPath);
		alipayConfig.setRootCertPath(alipayRootCertPath);
		alipayConfig.setPrivateKey(privateKey);
		alipayConfig.setServerUrl(paySetting.getThirdGatewayUrl());
		alipayConfig.setAppId(paySetting.getAppId());
		alipayConfig.setFormat("json");
		alipayConfig.setCharset("UTF8");
		alipayConfig.setSignType("RSA2");
		// 转账使用AES加密
        alipayConfig.setEncryptType("AES");
        alipayConfig.setEncryptKey(paySetting.getAesEncryptKey());
		return new DefaultAlipayClient(alipayConfig);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R reject(HbWithdrawRecordRejectReq req) throws Exception {
		HbWithdrawRecord record = this.getById(req.getId());
		if (record == null) {
			return R.failed("提现记录错误");
		}
		HbActivity hbActivity = activityService.getById(record.getActivityId());
		if (hbActivity == null) {
			return R.failed("活动信息错误");
		}
		HbCashConfig hbCashConfig = hbCashConfigMapper.selectById(record.getLevelId());
		if (hbCashConfig == null) {
			return R.failed("提现档次信息错误");
		}

		final Date now = new Date();
		HbWithdrawRecord updateBean1 = new HbWithdrawRecord();
		updateBean1.setId(req.getId());
		updateBean1.setAuditingId(Long.valueOf(SecurityUtils.getUser().getId()));
		updateBean1.setAuditingTime(now);
		updateBean1.setRejectReason(req.getRejectReason());
		if (baseMapper.updateStatusToRejectById(updateBean1) == 0) {
			return R.failed("提现状态错误");
		}
		hbActivityRoleInfoMapper.updateRejectOnceByRoleKey(new HbActivityRoleInfo()
				.setPgameId(record.getParentGameId().longValue()).setAreaId(record.getAreaId().longValue()).setRoleId(record.getRoleId()).setActivityId(record.getActivityId()).setSourceType(1)
				.setTotalWithdrawalAmount(record.getMoney()).setCashedRejectAmount(record.getMoney()));
		hbWithdrawRoleInfoMapper.updateRejectedOnceByRoleKey(new HbWithdrawRoleInfoDO().setPgameId(record.getParentGameId().longValue()).setAreaId(String.valueOf(record.getAreaId())).setRoleId(record.getRoleId()).setCashConfigId(record.getLevelId()));
		try {
			final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			final String recordValue = new JSONObject()
					.fluentPut("eventType", ActivityEventEnum.WITHDRAWAL_REJECT.getCode())
					.fluentPut("eventTime", sdf.format(now))
					.fluentPut("userId", record.getUserId())
					.fluentPut("username", record.getUsername())
					.fluentPut("pGameId", record.getParentGameId())
					.fluentPut("gameId", record.getGameId())
					.fluentPut("areaId", record.getAreaId())
					.fluentPut("parentChl", record.getParentchl())
					.fluentPut("chl", record.getChl())
					.fluentPut("appChl", record.getAppchl())
					.fluentPut("roleId", record.getRoleId())
					.fluentPut("roleName", record.getRoleName())
					.fluentPut("activityId", record.getActivityId())
					.fluentPut("activityName", hbActivity.getActivityName())
					.fluentPut("activityType", hbActivity.getActivityType())
					.fluentPut("dynamicTypeId", hbActivity.getDynamicTypeId())
					.fluentPut("stateType", updateBean1.getStatus())
					.fluentPut("levelId", record.getLevelId())
					.fluentPut("levelName", hbCashConfig.getCashName())
					.fluentPut("cashType", record.getType())
					.fluentPut("amount", record.getMoney().doubleValue())
					.fluentPut("receiveId", req.getId())
					.toJSONString();
			log.info("发送kafka信息减少累计提现金额:{}", recordValue);
			kafkaTemplate.send(properties.getActivityEventTopic(), String.valueOf(record.getUserId()), recordValue.getBytes(StandardCharsets.UTF_8));
		} catch (Exception e) {
			log.error("发送kafka信息减少累计提现金额异常", e);
			throw new Exception("发送kafka信息减少累计提现金额异常", e);
		}
		return R.ok();
	}

	/**
	 * MD5加密
	 *
	 * @param map
	 * @param keys
	 * @return
	 */
	private String createSign(Map<String, String> map, String keys) {
		String sign = "";
		try {
			List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
			// 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
			infoIds.sort((o1, o2) -> (o1.getKey()).compareTo(o2.getKey()));
			// 构造签名键值对的格式
			StringBuilder sb = new StringBuilder();
			for (Map.Entry<String, String> item : infoIds) {
				if (item.getKey() != null || item.getKey() != "") {
					String key = item.getKey();
					String val = item.getValue();
					if (!(val == "" || val == null)) {
						sb.append(key + "=" + val + "&");
					}
				}
			}
			String msg = sb.substring(0, sb.length() - 1).toString() + "&key=" + keys;//sb.substring(0,sb.length()-1).toString()：截取最后一个&
			//String result = (sb.toString().length()-1)+keys;
			log.info("================accsii排序===============" + msg);
			sign = MD5.sign(msg, "", "utf-8").toUpperCase();//MD5加密，toUpperCase()：大小写转换
			log.info("================signMD5加密===============" + sign);
		} catch (Exception e) {
			return null;
		}
		return sign;
	}


	/**
	 * 查询提现记录列表
	 * @param req
	 * @return
	 */
	@Override
	public IPage<HbWithdrawRecord> selectRecordPage(HbWithdrawRecordReq req){
		QueryWrapper<HbWithdrawRecord> query = new QueryWrapper<>();

		LambdaQueryWrapper<HbWithdrawRecord>  reqQ= query.lambda().like(StringUtils.isNotBlank(req.getUsername()), HbWithdrawRecord::getUsername, req.getUsername())
				.in(StringUtils.isNotBlank(req.getGameId()), HbWithdrawRecord::getGameId, req.getGameId())
				.eq(req.getAreaId() != null, HbWithdrawRecord::getAreaId, req.getAreaId())
				.eq(StringUtils.isNotBlank(req.getRoleId()), HbWithdrawRecord::getRoleId, req.getRoleId())
				.like(StringUtils.isNotBlank(req.getRoleName()), HbWithdrawRecord::getRoleName, req.getRoleName())
				.eq(req.getType() != null, HbWithdrawRecord::getType, req.getType())
				.eq(req.getStatus() != null, HbWithdrawRecord::getStatus, req.getStatus())
				.eq(StringUtils.isNotBlank(req.getMoney()), HbWithdrawRecord::getMoney, req.getMoney())
				.eq(HbWithdrawRecord :: getDeleted, 0)
				.orderByDesc(HbWithdrawRecord::getCreateTime);
		if(StringUtils.isNotBlank(req.getWithdrawTimeStart())){
			reqQ.apply("DATE_FORMAT(withdraw_time ,'%Y-%m-%d')  >= '" + req.getWithdrawTimeStart()+"'"  );
		}
		if(StringUtils.isNotBlank(req.getWithdrawTimeEnd())){
			reqQ.apply("DATE_FORMAT(withdraw_time ,'%Y-%m-%d')  <= '" + req.getWithdrawTimeEnd()+"'" );
		}
		if(StringUtils.isNotBlank(req.getPayedTimeStart())){
			reqQ.apply("DATE_FORMAT(payed_time ,'%Y-%m-%d')  >= '" +  req.getPayedTimeStart()+"'"  );
		}
		if(StringUtils.isNotBlank(req.getPayedTimeEnd())){
			reqQ.apply("DATE_FORMAT(payed_time ,'%Y-%m-%d')  <= '" +  req.getPayedTimeEnd()+"'"  );
		}
		// 处理数据
		IPage<HbWithdrawRecord> iPage = this.page(req, reqQ);
		this.dealData(iPage);
		return iPage;
	}


	/**
	 * 处理列表数据
	 * @param iPage
	 */
	public void dealData(IPage<HbWithdrawRecord> iPage){
		try {
			if (Objects.nonNull(iPage) && Objects.nonNull(iPage.getRecords())){
				List<HbWithdrawRecord> list = iPage.getRecords();
				// 获取父游戏列表
				Collection<Long> parentGameIds = list.stream().map(item -> {
					return Long.valueOf(String.valueOf(item.getParentGameId()));
				}).collect(Collectors.toSet());
				List<ParentGameDO> parentGameList = parentGameService.getCacheablePGameList(new ParentGameReq().setIds(parentGameIds));
				// 获取子游戏列表
				Collection<Long> gameIds = list.stream().map(item -> {
					return Long.valueOf(String.valueOf(item.getGameId()));
				}).collect(Collectors.toSet());
				gameIds.add(0L);
				List<WanGameDO> gameList = gameService.list(Wrappers.<WanGameDO>query().lambda().in(WanGameDO::getId,gameIds));


				List<HbActivity> activityList = activityService.list();

				for (HbWithdrawRecord hbWithdrawRecord : list){
					// 获取父游戏名称
					if (Objects.nonNull(parentGameList) && parentGameList.size() > 0) {
						parentGameList.forEach(game -> {
							if (hbWithdrawRecord.getParentGameId().intValue() == game.getId().intValue()) {
								hbWithdrawRecord.setParentGameName(game.getGname());
							}
						});
					}
					// 获取子游戏名称
					if (Objects.nonNull(gameList) && gameList.size() > 0) {
						gameList.forEach(game -> {
							if (hbWithdrawRecord.getGameId().intValue() == game.getId().intValue()) {
								hbWithdrawRecord.setGameName(game.getGname());
							}
						});
					}

					// 获取活动名称
					if (Objects.nonNull(activityList) && gameList.size() > 0) {
						activityList.forEach(hbActivity -> {
							if (hbWithdrawRecord.getActivityId().compareTo(hbActivity.getId()) == 0) {
								hbWithdrawRecord.setActivityName(hbActivity.getActivityName());
							}
						});
					}
					//将提现状态转换为提现状态描述
					if(null != hbWithdrawRecord.getStatus()){
						hbWithdrawRecord.setStatusName(WithdrawStatusEnum.getOneByVal(hbWithdrawRecord.getStatus()).getDesc());
					}
					//将提现方式转换为提现方式描述
					if(null != hbWithdrawRecord.getType()){
						hbWithdrawRecord.setTypeName(WithdrawTypeEnum.getOneByType(hbWithdrawRecord.getType()).getDesc());
					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}


